package com.masterclient.app.modules.pickgoods;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.modules.pickgoods.adapter.PickGoodsOrderListAdapter;
import com.masterclient.app.modules.pickgoods.beans.CheckOrderBean;
import com.masterclient.app.modules.pickgoods.beans.PickGoodsOrderBean;
import com.masterclient.app.modules.pickgoods.contract.PickGoodsOrderListContract;
import com.masterclient.app.modules.pickgoods.contract.PickGoodsOrderListPresenter;
import com.eoner.uikit.header.MyRefreshHead;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

@Route(path = AroutePath.PICK_GOODS_ORDER_LIST_FRAGMENT)
public class PickGoodsOrderListFragment extends BaseFragment<PickGoodsOrderListPresenter> implements PickGoodsOrderListContract.View {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.view_tip)
    View viewTip;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private TextView emptyTvTip;
    private int page = 1;
    private boolean hasMore;
    private View emptyView;
    private View footView;
    private List<PickGoodsOrderBean.ItemBean> list = new ArrayList<>();
    private PickGoodsOrderListAdapter pickGoodsOrderListAdapter;
    private SelectPickGoodsListener listener;
    private boolean isVisibleToUser = false;
    private String buyProduct = "";
    private String orderId = "";

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        listener.onCheckItem(orderId, buyProduct, isVisibleToUser);
    }

    public static PickGoodsOrderListFragment newInstance() {
        return new PickGoodsOrderListFragment();
    }

    public void setSelectPickGoodsListener(SelectPickGoodsListener listener) {
        this.listener = listener;
    }

    public static PickGoodsOrderListFragment getInstance(String type) {
        PickGoodsOrderListFragment pickGoodsListFragment = new PickGoodsOrderListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        pickGoodsListFragment.setArguments(bundle);
        return pickGoodsListFragment;
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        setFullScreenAndTransparent(getActivity());
        return inflater.inflate(R.layout.fragment_pick_goods_order_list, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();
        ARouter.getInstance().inject(this);

        refreshLayout.setRefreshHeader(new MyRefreshHead(getActivity()));
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            refresh();
        });

        pickGoodsOrderListAdapter = new PickGoodsOrderListAdapter((isCheck, orderId, buyProducts) -> {
            if (isCheck) {
                mPresenter.orderCheck(orderId);
                buyProduct = buyProducts;
                this.orderId = orderId;
                listener.onCheckItem(orderId, buyProduct, isVisibleToUser);
            } else {
                buyProduct = "";
                orderId = "";
                this.orderId = orderId;
                listener.onCheckItem("", "", isVisibleToUser);
            }
            for (int i = 0; i < list.size(); i++) {
                list.get(i).isChecked = orderId.equals(list.get(i).orderId) && isCheck;
            }
            pickGoodsOrderListAdapter.notifyDataSetChanged();
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(null);
        pickGoodsOrderListAdapter.bindToRecyclerView(recyclerView);

        emptyView = View.inflate(getActivity(), R.layout.null_collect, null);
        emptyTvTip= emptyView.findViewById(R.id.tv_tip);
        emptyTvTip.setText("您的代发商品是空的哦~");
        pickGoodsOrderListAdapter.setEmptyView(emptyView);
        emptyView.setVisibility(View.GONE);

        footView = View.inflate(mContext, R.layout.view_foot_text, null);
        footView.setVisibility(View.GONE);
        View viewFooter = footView.findViewById(R.id.view_footer);
        viewFooter.setBackgroundColor(Color.parseColor("#00000000"));
        pickGoodsOrderListAdapter.setFooterView(footView);
        pickGoodsOrderListAdapter.setOnLoadMoreListener(() -> {
            if (hasMore) {
                page++;
                mPresenter.getPickGoodsOrderListInfo(String.valueOf(page), PAGE_SIZE);
            }
        }, recyclerView);

        refresh();
    }

    private void refresh() {
        page = 1;
        mPresenter.getPickGoodsOrderListInfo(String.valueOf(page), PAGE_SIZE);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void showPickGoodsOrderListInfo(PickGoodsOrderBean bean) {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
        }

        buyProduct = "";
        orderId = "";
        listener.onCheckItem("", "", isVisibleToUser);
        if (!TextUtils.isEmpty(bean.topTips)) {
            tvTip.setText(bean.topTips);
            viewTip.setVisibility(View.VISIBLE);
        } else {
            viewTip.setVisibility(View.GONE);
        }

        setEmptyStatus(3);
        hasMore = bean.hasMore;
        if (list == null) {
            list = new ArrayList<>();
        }
        if (page == 1) {
            list.clear();
        }

        list.addAll(bean.items);
        pickGoodsOrderListAdapter.setNewData(list);
        if (list.size() <= 0) {
            setEmptyStatus(2);
        }
        if (list.size() > 0 && !hasMore) {
            pickGoodsOrderListAdapter.setEnableLoadMore(false);
            if (page != 1) {
                footView.setVisibility(View.VISIBLE);
            }
        } else {
            footView.setVisibility(View.GONE);
        }
        pickGoodsOrderListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onCheckSuccess(CheckOrderBean bean) {
        if (bean != null && !TextUtils.isEmpty(bean.errorTips)) {
            int type;
            if (bean.toPurchase) {
                type = 2;
            } else {
                type = 1;
            }
            ConfirmDialog confirmDialog = new ConfirmDialog(mContext, bean.errorTips, "取消", type == 2 ? "去采购" : "确定", type, "#FFFF6809");
            confirmDialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                @Override
                public void cancel() {
                    confirmDialog.dismiss();
                    checkDeal();
                }

                @Override
                public void confirm() {
                    confirmDialog.dismiss();
                    checkDeal();
                    if (type == 2) {
                        ARouter.getInstance().build(AroutePath.PURCHASE_ACTIVITY).navigation();
                    }
                }
            });
            confirmDialog.show();
        }
    }

    private void checkDeal() {
        for (int i = 0; i < list.size(); i++) {
            if (orderId.equals(list.get(i).orderId)) {
                list.get(i).isChecked = false;
            }
        }
        pickGoodsOrderListAdapter.notifyDataSetChanged();
        listener.onCheckItem("", "", isVisibleToUser);
    }

    @Override
    public void showFail(String msg) {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh(false);
        }
        setEmptyStatus(1);
        ToastUtil.showToast(msg);
    }

    @Override
    public void onCheckFail(String msg) {
        ToastUtil.showToast(msg);
    }

    /**
     * 设置页面置空状态
     *
     * @param status status == 1：code=15，页面加载失败
     *               status == 2：数据返回为空
     *               status == 3：数据返回正常
     */
    private void setEmptyStatus(int status) {
        if (status == 1) {
            emptyView.setVisibility(View.VISIBLE);
            emptyTvTip.setText("页面加载失败～");
        } else if (status == 2) {
            emptyView.setVisibility(View.VISIBLE);
            emptyTvTip.setText("暂无数据");
        } else {
            emptyView.setVisibility(View.GONE);
        }
    }

    public interface SelectPickGoodsListener {
        void onCheckItem(String orderId, String buyProducts, boolean isVisibleToUser);
    }
}
